package com.ti.shangou.service.impl;

import com.ti.shangou.dao.PermissionDao;
import com.ti.shangou.dao.RoleDao;
import com.ti.shangou.dao.UserDao;
import com.ti.shangou.pojo.dto.PageDTO;
import com.ti.shangou.pojo.dto.ResponseDTO;
import com.ti.shangou.pojo.entity.Role;
import com.ti.shangou.pojo.entity.User;
import com.ti.shangou.pojo.query.UserQuery;
import com.ti.shangou.pojo.vo.PermissionVO;
import com.ti.shangou.pojo.vo.RoleVO;
import com.ti.shangou.pojo.vo.UserVO;
import com.ti.shangou.service.UserService;
import com.ti.shangou.util.password.PasswordUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.xml.soap.Node;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 作者：田宝山
 * 日期：2020/5/29
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    RoleDao roleDao;
    @Resource
    UserDao userDao;
    @Resource
    PermissionDao permissionDao;


    public UserVO passwordLogin(UserQuery userQuery){
//        User user1 = userDao.selectByPrimaryKey( 1L);
        UserVO user = userDao.selectUserByTelAndPwd(userQuery);
        return  user;
    }
    public UserVO selectUserByPhone(UserQuery userQuery){
        return userDao.selectUserByPhone(userQuery.getPhone());
    }

    public UserVO selectUserByPhone(String phone){
        return userDao.selectUserByPhone(phone);
    }

    public int addUser(UserVO userVO){
        String encodePassword = PasswordUtil.encodePassword(userVO.getPassword());
        userVO.setPassword(encodePassword);
        int id = userDao.insertUser(userVO);
        return id;
    }


    public User selectUserById(Long userId) {
        return userDao.selectByPrimaryKey(userId);
    }

    public Integer updateUser(User user){
        return userDao.updateByPrimaryKeySelective(user);
    }

    public PageDTO ajaxList(UserQuery userQuery) {
        List<UserVO> userVOS = userDao.ajaxList(userQuery);
        Integer count = userDao.ajaxListCount();
        return PageDTO.setPageData(count,userVOS);
    }

    public List<RoleVO> selectHisRolesByPhone(String phone) {
        UserVO userVO = userDao.selectUserByPhone(phone);
        if (!StringUtils.isEmpty(userVO.getRoles())){
            List<RoleVO> roleVOS = roleDao.selectHisRolesByRoles(userVO.getRoles());
            if (!StringUtils.isEmpty(roleVOS)){
                List<PermissionVO> permissionVOList = permissionDao.selectPermissionsByRoleList(roleVOS);
                return setPermissionsOfRoles(roleVOS,permissionVOList);
            }
        }
        return null;
    }

    public ResponseDTO dispatchUserPermission(Long userId, List<Role> roles) {
        // 1、先把角色中的权限字符串取出来，因为要根据权限字符串去查询角色是否存在
        // 2、为了保险起见，应该让这些权限按照从小到大的顺序排序

        // 将流每个对象变为权限字符串的流, 实现Function接口，传入xx得到xx；
        Set<String> collect = roles.stream().map(r -> {
            String pStr = r.getPermissions();
            if (StringUtils.isEmpty(pStr)) {
                return "";
            } else {
                String[] split = pStr.split(",");
                // 数组排序，传入一个比较器
                Arrays.sort(split, Comparator.comparingInt(Integer::valueOf));
                // 将数组以','分隔变为字符串
                return StringUtils.arrayToDelimitedString(split, ",");
            }
        }).collect(Collectors.toSet());// 把所有角色中的权限字符串取出来当成一个查询参数set

        // 根据新集合中的权限查询对应角色集合
        List<Role> dbRoles = roleDao.selectRolesByPermissions(collect);
        Map<String, List<Role>> collect1 = dbRoles.stream().collect(Collectors.groupingBy(Role::getPermissions));

        TreeSet treeSet = new TreeSet();
        for (Role r : roles) {
            // 看数据库中的角色有没有这个权限组
            List<Role> roles1 = collect1.get(r.getPermissions());
            if (CollectionUtils.isEmpty(roles1)) {// 没有带这个权限组的角色，需要新增角色
                r.setSystem(false);
                r.setNote("==>新增分配角色：");
                roleDao.insertSelective(r);
                treeSet.add(r.getRoleId());
            } else {// 已经有这个权限组了，那么直接把这个权限组加入到事先准备好的treeSet里边
                treeSet.add(roles1.get(0).getRoleId());
            }
        }
        // 更新user，  将集合转为用符号分隔的字符串
        String s = StringUtils.collectionToDelimitedString(treeSet, ",");
        User u = new User();
        u.setUserId(userId);
        u.setRoles(s);
        return ResponseDTO.get(userDao.updateByPrimaryKeySelective(u) == 1);
    }

    public Integer deleteUsers(List<UserVO> userVOS) {
        return userDao.deleteUsers(userVOS);
    }
}
